
package www.wen.com.common.lib.util

import android.content.Context
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXTextObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import www.wen.com.common.BuildConfig.APPLICATION_ID
import www.wen.com.common.BuildConfig.WECHAT_APP_ID
import www.wen.com.common.lib.extension.toast


/**
 * @author WEN
 * @Description:
 * @date 2020/12/30 11:54
 */
object WxUtil {

    /**
     * 创建IWXAPI对象
     */
    fun getIWXAPI(context: Context): IWXAPI {
        val api = WXAPIFactory.createWXAPI(context, WECHAT_APP_ID, false)
        api.registerApp(WECHAT_APP_ID)
        return api
    }

    /**
     * 唤起微信登录
     * 微信用户授权的作用域 snsapi_userinfo、snsapi_base
     * 相关链接：https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
     */
    fun callWxLogin(api: IWXAPI) {
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = APPLICATION_ID
        api.sendReq(req)
    }

    /**
     * 微信分享文本
     * @param shareText 分享文本
     * @param isFriend 是否分享到朋友圈
     * @param action 发送到微信sdk成功返回
     */
    fun IWXAPI.shareText(shareText: String, isFriend: Boolean,action:((Boolean)->Unit)? = null):Boolean {

        if (!isWXAppInstalled) {
            toast("请先安装微信")
            return false
        }

        val textObject = WXTextObject().apply { text = shareText }

        val isSend = sendReq(SendMessageToWX.Req().apply {
            message = WXMediaMessage().apply {
                mediaObject = textObject
                description = shareText
            }
            transaction = buildTransaction("text")
            scene =
                if (isFriend) SendMessageToWX.Req.WXSceneTimeline else SendMessageToWX.Req.WXSceneSession
        })
        if(isSend){
            action?.invoke(isSend)
        }
        return isSend
    }

    private fun buildTransaction(@Suppress("SameParameterValue") str: String?): String? {
        return if (str == null) System.currentTimeMillis()
            .toString() else str + System.currentTimeMillis()
    }

}